import './order.css'
import {
  SearchOutlined,
  CloseCircleOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons'
import {
  Image,
  Tag,
  Pagination,
  Collapse,
  Button,
  Select,
  Input,
  Empty,
  Modal,
  ConfigProvider,
  DatePicker,
  Checkbox,
  message,
} from 'antd'
import zhCN from 'antd/locale/zh_CN'
import { useState, useCallback, useEffect } from 'react'
import {
  menuList,
  userOrderList,
  storeOrderList,
  foodlist,
  riderList,
  assignOrder,
  notDelivery,
} from '../../api/api'
import noting from '../../assets/noting.png'
import person from '../../assets/person.png'
import rider from '../../assets/rider.png'
import success from '../../assets/success.png'
import locale from 'antd/locale/zh_CN'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
import { BASE_URL } from '../../utils/config'
function FoodOrder(props) {
  const [arr, setArr] = useState([1])
  // console.log('props---', props)
  useEffect(() => {
    // getMenu()
    getFoodList()
    getList('all', 1)
  }, [arr])
  // 分页
  const [page, setPage] = useState(1)
  // 分页总页数
  const [pageTotal, setPageTotal] = useState(0)
  // 是否为空
  const [isEmpty, setEmpty] = useState(false)
  const [orderList, setOrderList] = useState([])
  // 获取订单列表
  const getList = (status, page) => {
    if (props.orderType == 1) {
      // 用户预订单列表，按菜品分类
      userOrderList({
        type: 1,
        food_id: foodId,
        // status: status,
        page: page,
        num: 50,
        nickname: nickname,
        order_no: orderNo,
        address: address,
        starttime: start,
        overtime: end,
      }).then((res) => {
        console.log('获取订单列表', res)
        if (res.data.data.length) {
          setEmpty(false)
          setPageTotal(res.data.total)
          res.data.data.forEach((item) => {
            item.check = false
          })
          setOrderList(res.data.data)
        } else {
          setEmpty(true)
          setPageTotal(res.data.total)
          setOrderList(res.data.data)
          return
        }
      })
    } else {
      // 销售网点预订单列表，按菜品分类

      storeOrderList({
        type: 1,
        /* menu_id: menu_id,
        status: status, */
        food_id: foodId,
        page: page,
        num: 50,
        nickname: nickname,
        order_no: orderNo,
        address: address,
        starttime: start,
        overtime: end,
      }).then((res) => {
        console.log('获取订单列表', res)
        if (res.data.data.length) {
          setEmpty(false)
          setPageTotal(res.data.total)
          res.data.data.forEach((item) => {
            item.check = false
          })
          setOrderList(res.data.data)
        } else {
          setEmpty(true)
          setPageTotal(res.data.total)
          setOrderList(res.data.data)
          return
        }
      })
    }
  }
  const [foodName, setFoodName] = useState(undefined)
  const [foodId, setFoodId] = useState('')
  const [foodArr, setFoodArr] = useState([])
  //获取菜品列表
  const getFoodList = () => {
    foodlist().then((res) => {
      console.log(res)
      setFoodArr(res.data)
    })
  }
  const [tabList, setTabList] = useState([])

  // 获取菜单
  const getMenu = () => {
    menuList().then((res) => {
      console.log(res)
      let allItem = {
        id: 0,
        name: '全部',
      }
      setTabList([allItem, ...res.data.list])
    })
  }
  // const [menuId, setMenuId] = useState('all')
  //设置默认当前选中
  const [current, setCurrent] = useState(0)
  //点击tab栏切换事件
  const clickevent = (e, item, index) => {
    // console.log('index---', index)
    setCurrent(index)
    // console.log('current---', current)
    const menuId = item.id == 0 ? 'all' : item.id
    getList(selectVal, page)
  }
  //选中的tab-content 内容添加active类名
  const classNameAdd = useCallback((cur) => {
    return current === cur ? 'active' : 'tabs__content'
  })
  // 右侧状态筛选
  const [selectVal, setSelectVal] = useState('all')
  const handleChange = (value) => {
    console.log(`selected ${value}`)
    // setSelectVal(value)
    console.log('---', current)

    // setCurrent(value)
    const obj = foodArr.find((item) => item.id == value)
    console.log(obj)
    setFoodId(value)
    setFoodName(obj.name)
    // const menuId = tabList[current].id == 0 ? 'all' : tabList[current].id
    // getList(menuId, value, page)
  }
  // 已完成弹窗
  const [fulfillOpen, setFulfillOpen] = useState(false)
  const showFulfillModal = () => {
    setFulfillOpen(true)
  }
  const handleFulfillCancel = () => {
    setFulfillOpen(false)
  }
  const [photoList, setPhotoList] = useState([])
  const [riderName, setRiderName] = useState('')
  // 查看配送中
  const checkDelivery = (item) => {
    showIndcModal()
    setRiderName(item.rider_name)
  }
  // 配送中弹窗
  const [indcOpen, setIndcOpen] = useState(false)
  const showIndcModal = () => {
    setIndcOpen(true)
  }
  const handleIndcCancel = () => {
    setIndcOpen(false)
  }
  // 查看照片
  const checkPhoto = (item) => {
    console.log(item)
    setPhotoList(item.photo)
    setRiderName(item.rider_name)
    showFulfillModal()
  }
  // 切换页码
  const onPageChange = (e) => {
    console.log('切换页码', e)
    setPage(e)
    getList(selectVal, e)
  }
  // 开始时间

  const [start, setStart] = useState('')
  const onChangeStart = (date, dateStr) => {
    console.log('开始时间', date, dateStr)
    setStart(dateStr)
  }
  // 结束时间

  const [end, setEnd] = useState('')

  const onChangeEnd = (date, dateStr) => {
    console.log('结束时间', date, dateStr)
    setEnd(dateStr)
  }
  // 用户名
  const [nickname, setNickname] = useState('')
  const handleNickname = (val) => {
    setNickname(val.target.value)
  }
  // 订单号
  const [orderNo, setOrderNo] = useState('')
  const handleOrderNo = (val) => {
    setOrderNo(val.target.value)
  }
  // 收货地址
  const [address, setAdderss] = useState('')
  const handleAddress = (val) => {
    setAdderss(val.target.value)
  }
  // 搜索
  const search = () => {
    console.log('当前', current)
    getList(selectVal, page)
  }
  const [dateKey, setDateKey] = useState(1)

  // 重置
  const reset = () => {
    console.log('重置数据')
    setStart('')
    setEnd('')
    setAdderss('')
    setFoodId('')
    setFoodName(undefined)
    setDateKey(2)
    setTimeout(() => {
      setDateKey(1)
    }, 0)
    setNickname('')
    setOrderNo('')
    setArr([])
  }
  // 数据导出
  const exportExcel = () => {
    if (props.orderType == 1) {
      //用户预订单数据导出
      console.log(orderList.length)
      if (orderList.length) {
        let url = `${BASE_URL}/kitchen/reserve/userReserveListExport?type=1&nickname=${nickname}&order_no=${orderNo}&food_id=${foodId}&address=${address}&starttime=${start}&overtime=${end}`
        window.open(url)
      }
    } else {
      if (orderList.length) {
        let url = `${BASE_URL}/kitchen/reserve/storeReserveListExport?type=1&nickname=${nickname}&order_no=${orderNo}&food_id=${foodId}&address=${address}&starttime=${start}&overtime=${end}`
        window.open(url)
      }
    }
  }
  // 多选
  const defaultCheckedList = []
  const handleCheck = (e, item, index) => {
    // console.log('123', e)

    if (item.check) {
      orderList[index].check = false
    } else {
      orderList[index].check = true
    }
    setOrderList([...orderList])

    // 判断是否全选
    const isEven = orderList.every((item, index) => {
      return item.check == true
    })
    if (isEven) {
      setChecked(true)
    } else {
      setChecked(false)
    }
  }
  const [deliveryOrderId, setDeliveryOrderId] = useState('')

  // 全选
  const onCheckAllChange = (e) => {
    if (checkAll == true) {
      setChecked(false)
      orderList.forEach((m) => {
        m.check = false
      })
    } else {
      setChecked(true)
      orderList.forEach((m) => {
        m.check = true
      })
    }
  }
  const [checkAll, setChecked] = useState(false)

  // 去配送
  const toDeliver = () => {
    let idArr = []
    let arr = orderList.filter((item) => {
      if (item.check) {
        idArr.push(item.id)
      }
    })
    showListModal()
    console.log(idArr)
    // return
    let idStr = idArr.join(',')
    setDeliveryOrderId(idStr)
  }
  // 骑手列表
  const [ridersList, setRidersList] = useState([])
  const [currentIndex, setCurrentIndex] = useState(0)
  // 获取骑手列表
  const getRiderList = () => {
    riderList().then((res) => {
      console.log('骑手列表', res)
      setRidersList(res.data.list)
    })
  }
  // 选择配送员弹窗
  const [listModalOpen, setListModalOpen] = useState(false)
  const showListModal = () => {
    setListModalOpen(true)
    getRiderList()
  }
  const handleListCancel = () => {
    setListModalOpen(false)
  }
  // 选择骑手
  const chooseRider = (e, index) => {
    console.log('当前索引', index)
    setCurrentIndex(index)
  }
  // 提交配送员
  const submitRider = () => {
    const rider_id = ridersList[currentIndex].id
    assignOrder({
      rider_id: rider_id,
      order_id: deliveryOrderId,
    }).then((res) => {
      console.log('分配订单', res)
      if (res.code == 200) {
        getList(selectVal, page)
        handleListCancel()
      }
    })
    showSuccessModal()
    // showIndcModal()
    // showFulfillModal()
  }
  // 提交成功弹窗
  const [successOpen, setSuccessOpen] = useState(false)
  const showSuccessModal = () => {
    setSuccessOpen(true)
  }
  const handleSuccessCancel = () => {
    getList()
    setSuccessOpen(false)
  }
  // 无法配送弹窗
  const [notModalOpen, setNotModalOpen] = useState(false)
  const showNotModal = () => {
    let idArr = []
    let arr = orderList.filter((item) => {
      if (item.check) {
        idArr.push(item.id)
      }
    })
    console.log(idArr)
    let idStr = idArr.join(',')
    setDeliveryOrderId(idStr)
    setNotModalOpen(true)
  }
  const handleNotCancel = () => {
    setNotModalOpen(false)
  }
  // 确认无法配送
  const confirmNot = () => {
    notDelivery({
      order_id: deliveryOrderId,
    }).then((res) => {
      console.log('无法配送', res)
      if (res.code == 200) {
        message.info(res.msg)
        handleNotCancel()
        getList(selectVal, page)
      }
    })
  }
  return (
    <div>
      {/* 确认无法配送弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={notModalOpen}
        onCancel={handleNotCancel}
        width="380px"
        height="380px"
        centered={true}>
        <p className="tc ft20">确认无法配送吗?</p>
        <div className="justify-between">
          <div className="cancelBtn btmbtn" onClick={handleNotCancel}>
            取消
          </div>
          <div className="confirmBtn btmbtn" onClick={confirmNot}>
            确认
          </div>
        </div>
      </Modal>
      {/* 提交成功弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={successOpen}
        onCancel={handleSuccessCancel}
        width="35%">
        <p className="tc ft20">提交成功</p>
        <div className="flex-col">
          <img src={success} className="successIcon" />
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {ridersList[currentIndex]?.nickname || ''}
          </div>
        </div>
      </Modal>
      {/* 选择配送员弹窗 */}
      <Modal
        title="选择配送员"
        footer={null}
        open={listModalOpen}
        onCancel={handleListCancel}
        width="80%">
        <div className="">
          <div className="grid5">
            {ridersList.map((item, index) => {
              return (
                <div
                  className="flex-col"
                  onClick={(e) => {
                    chooseRider(e, index)
                  }}
                  key={index}>
                  <Image
                    className={
                      currentIndex == index
                        ? ' border radius5 hidden riderimg'
                        : ' radius5 hidden riderimg'
                    }
                    width={154}
                    height={210}
                    preview={false}
                    src={item.avatar}
                  />
                  <div className="tc mt15">{item.nickname}</div>
                </div>
              )
            })}
          </div>

          <div className="submit-btn1" onClick={submitRider}>
            确认提交
          </div>
        </div>
      </Modal>
      {/* 已完成弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={fulfillOpen}
        onCancel={handleFulfillCancel}>
        <p className="tc ft20">已完成</p>
        <div className="">
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {riderName || ''}
          </div>
          <div className="align-center mt40 mb30">
            <div className="self-start">拍摄照片：</div>
            <div className="grid3">
              {photoList.map((item, index) => {
                return (
                  <div className="mr20" key={index}>
                    <Image width={100} src={item} />
                    {/* <Image.PreviewGroup items={photoList}>
                    <Image width={200} src={item} />
                  </Image.PreviewGroup> */}
                  </div>
                )
              })}
            </div>
          </div>
        </div>
      </Modal>
      {/* 配送中弹窗 */}
      <Modal
        title=" "
        footer={null}
        open={indcOpen}
        onCancel={handleIndcCancel}
        width="35%">
        <p className="tc ft20">正在配送中</p>
        <div className="flex-col">
          <img src={rider} className="riderIcon" />
          <div className="align-center mt40">
            配送员：
            <img src={person} className="personIcon ml10 mr10" />
            {riderName || ''}
          </div>
        </div>
      </Modal>
      <ConfigProvider
        theme={{
          components: {
            Button: {
              defaultActiveBg: '#f8c003',
              defaultActiveBorderColor: '#f8c003',
              defaultActiveColor: '#333333',
              defaultHoverBg: '#f8c003',
              defaultHoverBorderColor: '#f8c003',
              defaultHoverColor: '#333333',
              algorithm: true, // 启用算法
            },
          },
        }}>
        <div className=" tabbox justify-between">
          <div className="align-center flex-wrap" style={{ width: '70%' }}>
            <Input
              placeholder="请输入用户名"
              className="searchInput mr10 mb10"
              value={nickname}
              onChange={handleNickname}
            />
            <Input
              placeholder="请输入订单号"
              className="searchInput mr10 mb10"
              value={orderNo}
              onChange={handleOrderNo}
            />
            <Input
              placeholder="请输入收货地址"
              className="searchInput mr10 mb10"
              value={address}
              onChange={handleAddress}
            />
            <Select
              className="searchInput mr10 mb10"
              placeholder="请选择菜品类型"
              style={{
                borderRadius: '5px',
                overflow: 'hidden',
              }}
              value={foodName}
              onChange={handleChange}
              options={foodArr.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
            />
            <ConfigProvider locale={locale}>
              {dateKey == 1 ? (
                <div key={dateKey}>
                  <DatePicker
                    className="searchInput"
                    placeholder="开始时间"
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    onChange={onChangeStart}
                  />
                  <span className="ml10 mr10">--</span>
                  <DatePicker
                    className="mr10 searchInput"
                    placeholder="结束时间"
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    onChange={onChangeEnd}
                  />
                </div>
              ) : null}
            </ConfigProvider>
          </div>
          <div className="shrink0 mb10">
            <Button
              className="optbtn"
              icon={<SearchOutlined />}
              onClick={search}>
              查询
            </Button>
            <Button
              className="optbtn ml15"
              icon={<CloseCircleOutlined />}
              onClick={reset}
              style={{ background: '#f5f6fa', border: '1px solid #f5f6fa' }}>
              重置
            </Button>
            <Button
              icon={<UnorderedListOutlined />}
              onClick={exportExcel}
              className="optbtn ml15">
              导出
            </Button>
          </div>

          {/* <ul className="tabs-ul">
          {tabList.map((item, index) => {
            return (
              <li
                onClick={(e) => {
                  clickevent(e, item, index)
                }}
                key={index}>
                <div className={index == current && 'tabs-current'}>
                  {item.name}
                </div>
              </li>
            )
          })}
        </ul> */}
          {/* <div>
           <Select
            size="small"
            defaultValue="全部"
            style={{
              width: 120,
            }}
            onChange={handleChange}
            options={[
              {
                label: '全部',
                value: 'all',
              },
              {
                label: '待配送',
                value: '1',
              },
              {
                label: '配送中',
                value: '2',
              },
              {
                label: '待评价',
                value: '3',
              },
              {
                label: '已完成',
                value: '4',
              },
              {
                label: '退款中',
                value: '100',
              },
              {
                label: '已退款',
                value: '101',
              },
            ]}
          /> 
        </div> */}
        </div>
        {isEmpty ? (
          <div style={{ marginTop: '150px', minHeight: '500px' }}>
            <Empty image={noting} description="暂无数据" imageStyle={{}} />
          </div>
        ) : (
          <div>
            <Checkbox onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>

            {orderList.map((item, index) => {
              return (
                <div className="flex-row " key={index}>
                  {item.status == 1 ? (
                    <Checkbox
                      checked={item.check}
                      onChange={(e) => handleCheck(e, item, index)}
                      className="self-start mr15"></Checkbox>
                  ) : (
                    <div style={{ width: 31 }}></div>
                  )}

                  <div className="justify-between bggray mb20 radius10 pd20 flex1">
                    <div className="">
                      <div className="flex-wrap">
                        {item.foods.map((ite, ind) => {
                          return (
                            <div className="mr15 mb15" key={ind}>
                              <div
                                className="flex-cen hidden"
                                style={{
                                  height: 108,
                                  background: '#ffffff',
                                  width: 108,
                                  borderRadius: '10px',
                                }}>
                                <Image width={108} src={ite.food_image} />
                              </div>

                              <div className="ft18 mt5">
                                {ite.food_name}
                                {/* <Tag className="ml10 mytag">预订单</Tag> */}
                              </div>
                              <div className="mt5 gray9 ft16">
                                x{ite.number}
                              </div>
                            </div>
                          )
                        })}
                      </div>

                      <div className="mt20 ft14 gray6">
                        <span>收货人:{item.nickname}</span>
                        <span className="ml20">订单编号:{item.order_sn}</span>
                        <span className="ml20">
                          下单时间:{item.createtime_text}
                        </span>
                        <span className="ml20">联系方式:{item.mobile}</span>
                        <span className="ml20">
                          下单地址:{item.address}
                          {item.expand}
                        </span>
                      </div>
                    </div>
                    <div className="self-start align-center">
                      {item.photo && item.status_text != '配送中' ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkPhoto(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      {item.status_text == '配送中' ? (
                        <div
                          className="deliverBtn pointer"
                          onClick={() => checkDelivery(item)}
                          style={{ marginRight: '10px' }}>
                          查看
                        </div>
                      ) : null}
                      <div className="">{item.status_text}</div>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}
        <div className="flex-cen mt10">
          <ConfigProvider locale={zhCN}>
            <Pagination
              total={pageTotal}
              showSizeChanger={false}
              showQuickJumper
              defaultPageSize={50}
              onChange={(e) => onPageChange(e)}
              showTotal={(total) => `共 ${total} 条`}
            />
          </ConfigProvider>
        </div>
        {orderList.length ? (
          <div className="mt30 flex-col">
            <div className="mlauto flex">
              <Button
                className="optbtn mlauto"
                onClick={showNotModal}
                style={{
                  width: 140,
                  height: 50,
                  background: '#f5f6fa',
                  border: '1px solid #f5f6fa',
                }}>
                无法配送
              </Button>

              <Button
                className="optbtn mlauto ml20"
                onClick={toDeliver}
                style={{ width: 140, height: 50 }}>
                去配送
              </Button>
            </div>
          </div>
        ) : null}
      </ConfigProvider>
    </div>
  )
}
export default FoodOrder
